package client.gui;

import javax.print.attribute.standard.Chromaticity;
import javax.swing.*;
import javax.swing.event.AncestorEvent;
import javax.swing.event.AncestorListener;
import javax.swing.table.DefaultTableModel;

import client.GetFileFromServer;
import client.SendFileToServer;

import sharedspace.*;

import java.awt.Dimension;
import java.awt.Font;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import messages.*;

import java.util.*;

/**
 * This JPanel is a panel for Teacher to approve students executive test grades
 * @author Amir S.
 * @author Jacob C.
 * @author Maya G.
 * @author Michael V.
 *
 */

public class GUI_TeacherApprovingGrade extends JPanel{
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private Teacher teacher;
	private Client_GUI ms;
	public JButton btnBack;
	private GUI_Teacher_StudentTestView testFrame;
	private JButton testButton;
	private JButton changeGrade;
	private JButton confirmGrade;
	private JButton cheatersButton;
	private JButton refresh;
	private JLabel titleLabel;
	private JScrollPane examToApproveScroller = null;
	private JTable examToApproveTable = null;
	private DefaultTableModel model;
	public List<ApprovingGrade> aList;
	private List<ExecuteTest> eList;
	private List<Cheaters> cList;
	public boolean b=true;
	private GUI_ImagePanel background;
	
	
	public GUI_TeacherApprovingGrade(Client_GUI ms, User user){
		super();
		this.ms = ms;
		this.teacher = new Teacher(user);
		
		getApprovedTest();
		for (int i=0;i<aList.size(); i++)
		{
			String[] comment = new String[aList.get(i).getStudentInTest().getChoises().size()];
			aList.get(i).setTeacherComment(comment);
		}
		if (aList.size()==0)
		{
			JOptionPane.showMessageDialog(null, "No Test To Approve");
			b=false;
		}
		else this.initilized();
		
	}
	/**
	 * Initialize screen
	 */
	public void initilized()
	{
		background = new GUI_ImagePanel(new ImageIcon("images/background1.jpg").getImage());
		background.setSize(new Dimension(1000, 700));
		add(background);
		
		btnBack = new JButton("Back");
		btnBack.setFont(new Font("Arial", Font.PLAIN, 16));
		btnBack.setBounds(118, 582, 99, 34);
		
		titleLabel = new JLabel("Approving Grades");
		titleLabel.setForeground(new Color(0, 0, 204));
		titleLabel.setFont(new Font("Arial", Font.BOLD | Font.ITALIC, 50));
		titleLabel.setSize(474, 78);
		titleLabel.setLocation(289, 34);
		this.setLayout(null);
		this.setSize(1000, 700);
		background.add(btnBack);
		background.add(titleLabel);
		background.add(getTestButton());
		background.add(getChangeGrade());
		background.add(getConfirmGrade());
		background.add(getCheatersButton());
		background.add(getApproveTable());
		//add(getRefreshButton());
		
	}
	/**
	 * make table of student who's test need to be approve
	 * @return
	 */
	public JScrollPane getApproveTable()
	{
		if (examToApproveTable == null)
		{
			String columnNames[] =  {"TestID","Subject Name","Course Name","Studnet Name","Computerized Grade", "Manual Test Location"};
			String[][] tableModel = new String[aList.size()][6];
			
			for (int i = 0; i<aList.size(); i++)
			{
				tableModel[i][0] = aList.get(i).getExecuteTest().getTest().getTestID();
				tableModel[i][1] = aList.get(i).getExecuteTest().getTest().getSubject().getSubjectName();
				tableModel[i][2] = aList.get(i).getExecuteTest().getTest().getCourse().getCourseName();
				tableModel[i][3] = aList.get(i).getStudentInTest().getStudent().getUserFirstName() + " "
								 + aList.get(i).getStudentInTest().getStudent().getUserLastName(); 
				if (aList.get(i).getStudentFianlGrade() == -1)
					tableModel[i][4] = "Test is manula";
				else tableModel[i][4] = Integer.toString(aList.get(i).getStudentFianlGrade());
				if (aList.get(i).getStudentInTest().getWordTestCheckedPath()== null)
					tableModel[i][5] = "Test is computerized";
				else tableModel[i][5] = aList.get(i).getStudentInTest().getWordTestCheckedPath(); 
			}
			
			
			model = new DefaultTableModel(tableModel, columnNames){
				   /**
				 * 
				 */
				private static final long serialVersionUID = 1L;

				public boolean isCellEditable(int rowIndex, int colIndex) {
				   return false; //Disallow the editing of any cell
				   }
				   };

			examToApproveTable = new JTable(model);
			examToApproveTable.setFont(new Font("Tahoma", Font.PLAIN, 14));
			examToApproveTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
			examToApproveTable.getTableHeader().setReorderingAllowed(false);
			examToApproveScroller = new JScrollPane(examToApproveTable);
			examToApproveScroller.setBounds(50, 150, 900, 400);
			
		}
		
		return examToApproveScroller;
	}
	/**
	 * make button to display test of student
	 * @return
	 */
	public JButton getTestButton()
	{
		testButton = new JButton("Show Test ");
		testButton.setBounds(449, 113, 100, 30);
		testButton.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent arg0) {
				// TODO Auto-generated method stub
				System.out.println(examToApproveTable.getSelectedRow());
				if (aList.size()==0)
					JOptionPane.showMessageDialog(null, "No Test");
				else
				{
					int i = examToApproveTable.getSelectedRow();
					if (aList.get(i).getStudentInTest().getWordTestCheckedPath()==null)
					{	/*test is computerized and new window of test will be open*/
						testFrame = new GUI_Teacher_StudentTestView(ms,aList.get(i).getStudentInTest().getChoises(),i);
						confirmGrade.setEnabled(true);
						testFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
						testFrame.setResizable(true);
						testFrame.setVisible(true);
					}
					else
					{	/*test is manual, teacher need to download it to check it*/
						MessageGetStudentWordFile msggswf = new MessageGetStudentWordFile(aList.get(i).getStudentInTest().getWordTestCheckedPath());
						try {
							ms.client.sendToServer(msggswf);
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						MyFile myFile = (MyFile)ms.client.GetMessage();
						File file = FileHandler.saveFileDialog("Save Test");
						String path = file.getAbsolutePath();
					    GetFileFromServer gffs = new GetFileFromServer(path);
						gffs.getFileFromServer(myFile);
								
					    
					}
				}
			}
		});
		
		
		return testButton;
	}
	/**
	 * button to change grade of test
	 * @return
	 */
	public JButton getChangeGrade()
	{
		
		changeGrade = new JButton("Change Grade");
		changeGrade.setBounds(555, 113, 130, 30);
		changeGrade.addActionListener(new ActionListener() {
		String string;
		int grade;
			@Override
			public void actionPerformed(ActionEvent arg0) {
				// TODO Auto-generated method stub
				if (aList.size()==0)
					JOptionPane.showMessageDialog(null, "No Test");
				else
				{
					int i = examToApproveTable.getSelectedRow();
					string = JOptionPane.showInputDialog("Change Grade");
					try
					{
						grade = Integer.parseInt(string);
						if (grade>=0 && grade <=100)
						{
							string = JOptionPane.showInputDialog("Type reason for changing grade");
							if (string==null || string.equals(""))
							{
								JOptionPane.showMessageDialog(null, "no reason enterd\n change grade again");
								return;
							}
							examToApproveTable.setValueAt(Integer.toString(grade), i, 4);
							aList.get(i).setStudentFianlGrade(grade);
							aList.get(i).setTeacherApprove(false);
							aList.get(i).setTeacherCommentForGrade(string);
							confirmGrade.setEnabled(true);
						}
					else JOptionPane.showMessageDialog(null, "Invalid Grade");
					}
					catch(NumberFormatException e)
					{
						JOptionPane.showMessageDialog(null, "Invalid Input");
					}
					
					
				}
				
				
			}
		});
		
		return changeGrade;
	}
	/**
	 * button to confirm grade
	 * @return
	 */
	public JButton getConfirmGrade()
	{
		confirmGrade = new JButton("Confirm Grade");
		confirmGrade.setBounds(313, 113, 130, 30);
		confirmGrade.setEnabled(false);
		confirmGrade.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent arg0) {
				// TODO Auto-generated method stub
				if (aList.size()==0)
					JOptionPane.showMessageDialog(null, "No Test");
				else
				{	
					int i = examToApproveTable.getSelectedRow();
					int option = JOptionPane.showConfirmDialog(null, "This will be the final grade!\n" +
																	  "Are you sure?", "Confirming Grade", JOptionPane.YES_NO_OPTION);
					if (option==JOptionPane.YES_OPTION)
					{
						
						if (aList.get(i).getStudentInTest().getWordTestCheckedPath()==null)						
						{	/*teacher confirm grade for computerized test*/
							MessageFinalGrade msgfg = new MessageFinalGrade(aList.get(i));
							try
							{
								ms.client.sendToServer(msgfg);
							}
							catch (IOException e)
							{
							// TODO Auto-generated catch block
							e.printStackTrace();
							}
							model.removeRow(i);
							aList.remove(i);
							confirmGrade.setEnabled(false);
						}
						else 
						{	/*teacher confirm grade for manual test, and send test checked to server */
							File file = FileHandler.openFileDialog("Uplaod Test");
							
								String path = file.getAbsolutePath();
								System.out.println(path);
								SendFileToServer sfts = new SendFileToServer(path);
								MyFile myFile = sfts.sendFileToServer(aList.get(i).getExecuteTest(), aList.get(i).getStudentInTest().getStudent());
								MessageFinalGrade msgfg = new MessageFinalGrade(myFile, aList.get(i));
								try {
									ms.client.sendToServer(msgfg);
								} catch (IOException e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									}
								model.removeRow(i);
								aList.remove(i);
								confirmGrade.setEnabled(false);
							
									    
						}
						
					}
					
				}
				
			}
		});
		return confirmGrade;
	}
	/**
	 * button to show cheater list
	 * @return
	 */
	public JButton getCheatersButton()
	{
		cheatersButton = new JButton("Check for cheaters");
		cheatersButton.setBounds(691, 113, 150, 30);
		if (aList.size()<=1)
			cheatersButton.setEnabled(false);
		else
		{
			cheatersButton.setEnabled(true);
			cheatersButton.addActionListener(new ActionListener() {
				
				@Override
				public void actionPerformed(ActionEvent arg0) {
					// TODO Auto-generated method stub
					
					try {
						MessageCheatersCheck msgcc = new MessageCheatersCheck(teacher.getUserID());
						ms.client.sendToServer(msgcc);
						MessageCheatersCheckReply msgccrep = (MessageCheatersCheckReply)ms.client.GetMessage();
						cList = msgccrep.getcList();
						if (cList.size() == 0)
							JOptionPane.showMessageDialog(null, "No Cheater for the following test\n No sinners in your class");
						else
						{	/*open cheaters list in new window*/
							GUI_CheatersTable cheatersTableFrame= new GUI_CheatersTable(cList);
							cheatersTableFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
							cheatersTableFrame.setResizable(true);
							cheatersTableFrame.setVisible(true);
						}
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
					
					
				}
			});
		}
		return cheatersButton;
	}
	
	/**
	 * send message to server to get all test teacher need to approve
	 */
	public void getApprovedTest()
	{
		try{
			MessageApprovedTest msgat = new MessageApprovedTest(teacher.getUserID());
			ms.client.sendToServer(msgat);
			
		}
		catch(IOException e)
		{
			e.printStackTrace();
		}
		MessageApprovedTestReply msatrep = (MessageApprovedTestReply)ms.client.GetMessage();
		aList = msatrep.getAlist();
		
	}
	

	
	

}
